package com.sec.etech.ism.service.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.sec.etech.common.constant.DBConstant;
import com.sec.etech.common.util.RequestHolder;
import com.sec.etech.ism.constant.SignatureConstant;
import com.sec.etech.ism.service.IsmMethodService;
import com.sec.etech.sys.util.DbUtil;
import lombok.extern.slf4j.Slf4j;
import org.openbpm.base.api.exception.BusinessMessage;
import org.openbpm.form.util.DateUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class IsmGetProcessInfoByComNumServiceImpl implements IsmMethodService {

    public IsmGetProcessInfoByComNumServiceImpl() {
    }

    @Override
    public JSONObject call(String sysCode, String serviceCode, JSONObject businessParams) throws Exception {
        JSONObject result = new JSONObject();
        String componentNum = this.checkAndGetData(businessParams);
        List<JSONObject> resList = this.getProcessInfoByComNum(componentNum);
        result.put("flag", "success");
        result.put("data", resList);
        return result;
    }

    private String checkAndGetData(JSONObject busParams) throws BusinessMessage {
        JSONObject object = busParams.getJSONObject(SignatureConstant.INPUT_PARAMS);
        if (object.get("componentNum") == null || object.getString("componentNum").length() == 0) {
            throw new BusinessMessage("请求中缺少参数，请检查！");
        }
        return object.getString("componentNum");
    }

    private List<JSONObject> getProcessInfoByComNum(String componentNum) throws Exception {

        JdbcTemplate slaveJdbcTemplate = DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE);
        String sql = "select t1.processid,t1.num,t1.processname,t2.plantasknum,t2.plantaskname,t1.finishdate,t1.versions,t3.typename " +
                "from proc_process t1 join proj_plantask t2 on t1.plantaskid=t2.plantaskid " +
                " join proc_process_z_type t3 on t1.typeid=t3.typeid " +
                "where t1.statusid in (4,6) and t1.typeid>0 and t1.typeid<12 and t1.active=1 and t2.plantasknum=?";
        List<Map<String, Object>> processList = slaveJdbcTemplate.queryForList(sql, componentNum);
        if (processList == null || processList.size() == 0) {
            return new ArrayList<>();
        }
        List<JSONObject> resList = new ArrayList<>();
        for (Map<String, Object> map : processList) {
            JSONObject object = new JSONObject();
            object.put("processNum", map.get("num"));
            object.put("processName", map.get("processname"));
            object.put("versions", map.get("versions"));
            object.put("processType", map.get("typename"));
            object.put("componentNum", map.get("plantasknum"));
            object.put("componentName", map.get("plantaskname"));
            if (map.get("finishdate") != null) {
                object.put("finishDate", DateUtils.format((Date) map.get("finishdate"), "yyyy-MM-dd"));
            } else {
                object.put("finishDate", "");
            }
            String fileId = this.getLatestFileProcess(object.getLong("processId"));
            if (fileId != null && !"".equals(fileId)) {
                object.put("fileUrl", RequestHolder.getUrl() + "/sys/sysFile/preview.html?fileId=" + fileId +
                        "&withWatermark=1&audience=drawing");
            } else {
                object.put("fileUrl", "");
            }
            resList.add(object);
        }
        return resList;
    }

    /**
     * 获取最新版本的文件ID
     *
     * @param processId
     * @return
     */
    private String getLatestFileProcess(Long processId) {
        String fileId = null;
        String sql = "select t.fileid,t.filename,max(t.version) maxversion from " +
                "(SELECT t2.id_ fileid,left(t2.name_,char_length(t2.name_)-locate('.',reverse(t2.name_))) filename,t1.version FROM file_process t1, sys_file t2 " +
                "where t1.uploadseries=t2.id_ and t1.active=1 and t1.processid=? order by t1.version desc,t1.postdate desc limit 1000) t";
        List<Map<String, Object>> dbList = DbUtil.getJdbcTemplate().queryForList(sql, processId);
        if (dbList.size() > 0) {
            fileId = MapUtil.getStr(dbList.get(0), "fileid");
        }
        return fileId;
    }

    @Override
    public String methodName() {
        return "getProcessInfoByComNum";
    }
}
